<template>
  <div class="exam-container">
    <div class="real-content flex flex-align-start flex-row u-font-18">
      <!-- 信息 -->
      <div>
        <div class="real-content__title">
          <div class="real-content_title_top">{{ userStore.storeInfo.storeName }}</div>
          <div class="w500 center">第01考台</div>
        </div>
        <div class="real-content__info flex flex-column flex-align-start">
          <div class="real-content_title_top">
            考生信息
          </div>
          <img :src="userStore.storeInfo.avatar" alt="" class="headerImg">
          <div class="u-m-t-20 flex flex-row flex-align-start">
            <div style="white-space: nowrap;">姓名：</div>
            <div class="u-flex-1" style="word-break: break-all;">{{ userStore.storeInfo.memberName }}</div>
          </div>
          <div class="u-m-t-5">性别：男</div>
          <div class="u-m-t-5">类型：小车</div>
          <div class="u-m-t-5">科目：科目一</div>
        </div>
        <div class="real-content__count center">
          <div class="real-content_title_top">剩余时间</div>
          <span>{{ formatTime(countdown) }}</span>
        </div>
      </div>
      <!-- 考题 -->
      <div>
        <div class="real-content__question">
          <div class="examTips">考试题目</div>
          <div class="flex flex-column flex-justify-between" style="width: 50%;">
            <div class="real-content__question-body" v-if="currentQuestion">
              <div class="w-500" style=" color: '#333' ">
                <!-- 判断题型 -->
                <div class="exam-type-btn">
                  {{ currentQuestion.questionType === 0 ? '多选' : currentQuestion.questionType === 1 ? '单选' : '判断' }}
                </div>
                <span>{{ isWrongQuestionsMode ? currentWrongIndex + 1 : currentIndex + 1 }}. {{
                  currentQuestion.questionName }}</span>
                <!-- <span class="collect" @click="currentQuestion.isCollected = !currentQuestion.isCollected">
                  <img :src="currentQuestion && !currentQuestion.isCollected ? isCollected : collected" alt=""
                    class="img-20">
                  {{ currentQuestion && !currentQuestion.isCollected ? '收藏' : '已收藏' }}
                </span> -->
              </div>
              <div>
                <div class="u-m-t-30 flex flex-row flex-align-center" v-for="(option, key) in options" :key="key">
                  <div class="u-m-r-20" v-if="currentQuestion.questionType !== 2">{{ key }}</div>
                  <div v-if="currentQuestion.questionType <= 1">
                    {{ option }}
                  </div>
                  <div v-else>{{ option === '正确' ? '✓' : option === '错误' ? '×' : option }}</div>
                </div>
              </div>
            </div>
            <div class="real-content__answer" v-if="currentQuestion">
              <div class="selectAnswer c-blue">
                您选择的答案：
                <template v-if="currentQuestion.questionType === 2">
                  {{ currentQuestion.userAnswer === 'A' ? '✓' : currentQuestion.userAnswer === 'B' ? '×' :
                    currentQuestion.userAnswer }}
                </template>
                <template v-else-if="currentQuestion.questionType === 0">
                  <span v-if="Array.isArray(currentQuestion.userAnswer)">
                    {{ currentQuestion.userAnswer.length ? currentQuestion.userAnswer.slice().sort().join('') : '' }}
                  </span>
                  <span v-else>
                    {{ currentQuestion.userAnswer || '' }}
                  </span>
                </template>
                <template v-else>
                  {{ currentQuestion.userAnswer }}
                </template>
                <div v-if="showAnswer">
                  <span class="c-black">正确答案：</span>
                  <span class="c-red">
                    <template v-if="currentQuestion.questionType === 2">
                      {{ currentQuestion.answer === 'A' ? '✓' : currentQuestion.answer === 'B' ? '×' :
                        currentQuestion.answer }}
                    </template>
                    <template v-else-if="currentQuestion.questionType === 0">
                      <span v-if="Array.isArray(currentQuestion.answer)">
                        {{ currentQuestion.answer.slice().sort().join('') }}
                      </span>
                      <span v-else>
                        {{ currentQuestion.answer }}
                      </span>
                    </template>
                    <template v-else>
                      {{ currentQuestion.answer }}
                    </template>
                  </span>
                </div>
              </div>
              <div class="options">
                <div class="u-font-30 float-l">选项：</div>
                <div v-for="(option, key) in options" :key="key" class="real-content__answer-item center" :class="{
                  selectedAnswer:
                    currentQuestion.questionType === 0
                      ? (Array.isArray(currentQuestion.userAnswer) && currentQuestion.userAnswer.includes(String(key)))
                      : currentQuestion.userAnswer === String(key)
                }" @click="chooseAnswer(key)">
                  <div v-if="currentQuestion.questionType <= 1">{{ key }}</div>
                  <div v-else>{{ option === '正确' ? '✓' : option === '错误' ? '×' : option }}</div>
                </div>
              </div>
            </div>
          </div>
          <!-- 选题 -->
          <div>
            <div class="imagetable">
              <div class="th flex flex-row flex-align-center">
                <div class="td bg-blue" v-for="(item, index) in tdHeader" :key="index">{{ item }}</div>
              </div>
              <!-- 新的选题遍历方式：根据 questionList.value 生成行和列 -->
              <div v-for="(row, rowIndex) in questionTableRows" :key="rowIndex" class="flex flex-align-center th">
                <div class="td bg-blue">{{ rowIndex + 1 }}行</div>
                <div class="td" v-for="(q, colIndex) in row" :key="colIndex" :class="[
                  { selected: (isWrongQuestionsMode ? currentWrongIndex : currentIndex) === q.index },
                  !isSelectedCell(q.index) && isCorrect(q.index) ? 'correct' : '',
                  !isSelectedCell(q.index) && isWrong(q.index) ? 'wrong' : '',
                  !isSelectedCell(q.index) && !isCorrect(q.index) && !isWrong(q.index) && getUserAnswer(q.index) ? 'answered' : ''
                ]" @click="selectQuestion(q.index)">
                  <span :class="{
                    'u-font-15': String(getUserAnswer(q.index)).length > 2,
                    'u-font-30': String(getUserAnswer(q.index)).length <= 2
                  }">
                    {{ getUserAnswer(q.index) }}
                  </span>
                </div>
                <!-- 补齐空格 -->
                <div v-for="empty in 10 - row.length" :key="'empty-' + empty" class="td"
                  style="background: transparent; border: none;"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="real-content__reply flex flex-row flex-justify-between flex-align-center" v-if="currentQuestion">
      <div>
        <div class="u-font-18 c-red">操作提示：{{ currentQuestion.questionType === 0 ? '多选题' :
          currentQuestion.questionType
            === 1
            ?
            '单选题' : '判断题' }} </div>
        <div class="u-font-18 u-m-t-10">本题为{{ currentQuestion.questionType === 0 ? '多选题' : currentQuestion.questionType
          ===
          1 ?
          '单选题' :
          '判断题' }}，请{{
            currentQuestion.questionType === 0 ? '在选项中选择你认为正确的答案' : currentQuestion.questionType === 1 ? '选出正确的答案' :
              '判断对错' }}
        </div>
      </div>
      <div class="flex flex-row flex-justify-around flex-align-center">
        <button class="real-content__reply-btn" @click="goPrev"
          :class="(isWrongQuestionsMode ? currentWrongIndex == 0 : currentIndex == 0) ? 'boundary_button' : 'default_button'">
          <span>上一题</span>
        </button>
        <button class="real-content__reply-btn u-m-l-20" @click="goNext" :class="(isWrongQuestionsMode ? currentWrongIndex == wrongQuestionsList.length - 1 : currentIndex == questionList.length - 1) ? 'boundary_button' : 'default_button'
          ">
          <span>下一题</span>
        </button>
        <button class="real-content__reply-btn u-m-l-20" @click="handleSubmitClick">
          <span>交卷</span>
        </button>
      </div>
    </div>
    <div class="q-img flex flex-row flex-align-center flex-justify-center" v-if="currentQuestion">
      <el-image :src="currentQuestion.questionImg" :preview-src-list="[`${currentQuestion.questionImg}`]"
        v-if="currentQuestion.questionImg" :hide-on-click-modal="true" />
    </div>
    <div class="exam-confirm-modal" v-if="isVisible">
      <div class="modal-content">
        <div class="modal-title">考试确认窗口</div>
        <div class="operation-tips">
          <p class="u-m-b-26">操作提示：</p>
          <p class="u-m-b-16">你当前考试答对{{ correctNum }}题，答错{{ wrongNum }}题，未答{{ unansweredCount }}题。</p>
          <div class="u-m-b-16">点击【确认交卷】，将提交考试成绩，结束考试！</div>
          <div class="u-m-b-16">点击【继续考试】，将关闭本窗口，继续考试！</div>
        </div>
        <div class="button-group">
          <button class="confirm-btn u-m-r-30" @click="submitExam">确认交卷</button>
          <button class="confirm-btn" @click="continueExam">继续考试</button>
        </div>
      </div>
    </div>
    <div class="modal-mask" v-if="wrongVisible">
      <div class="modal-wrapper">
        <div class="wrong-modal-title">错题学习</div>
        <div class="wrong-modal-content">
          <div class="question-title">
            {{ currentIndex + 1 }}. {{ currentQuestion.questionName }}
          </div>
          <div class="question-options">
            <div class="u-m-t-20 flex flex-row flex-align-center" v-for="(option, key) in options" :key="key">
              <div class="u-m-r-20" v-if="currentQuestion.questionType === 1">{{ key }}</div>
              <div>{{ option === '正确' ? '✓' : option === '错误' ? '×' : option }}</div>
            </div>
          </div>
          <img v-if="currentQuestion.questionImg" :src="currentQuestion.questionImg"
            :preview-src-list="[`${currentQuestion.questionImg}`]" class="question-img" />
        </div>
        <div class="modal-bottom">
          <div class="modal-answer">
            <span class="right">正确答案：
              <template v-if="currentQuestion.questionType === 2">
                {{ currentQuestion.answer === 'A' ? '✓' : currentQuestion.answer === 'B' ? '×' : currentQuestion.answer
                }}
              </template>
              <template v-else-if="currentQuestion.questionType === 0">
                <span v-if="Array.isArray(currentQuestion.answer)">
                  {{ currentQuestion.answer.slice().sort().join('') }}
                </span>
                <span v-else>
                  {{ currentQuestion.answer }}
                </span>
              </template>
              <template v-else>
                {{ currentQuestion.answer }}
              </template>
            </span>
            <span class="wrong-select">您的答案：
              <template v-if="currentQuestion.questionType === 2">
                {{ currentQuestion.userAnswer === 'A' ? '✓' : currentQuestion.userAnswer === 'B' ? '×' :
                  currentQuestion.userAnswer }}
              </template>
              <template v-else-if="currentQuestion.questionType === 0">
                <span v-if="Array.isArray(currentQuestion.userAnswer)">
                  {{ currentQuestion.userAnswer.length ? currentQuestion.userAnswer.slice().sort().join('') : '' }}
                </span>
                <span v-else>
                  {{ currentQuestion.userAnswer || '' }}
                </span>
              </template>
              <template v-else>
                {{ currentQuestion.userAnswer }}
              </template>
            </span>
          </div>
          <div class="modal-footer">
            <button @click="closeModal">确定</button>
          </div>
          <div class="countdown-tip">
            页面将在{{ wrongCountDown }}秒后自动关闭，返回考试主界面
          </div>
        </div>
      </div>
    </div>

    <!-- 考试结果弹框 -->
    <div class="modal-mask" v-if="examResultVisible">
      <div class="exam-result-modal">
        <div class="exam-result-content">
          <div class="exam-result-header">
            <h2 class="exam-result-title">本次考试不合格</h2>
          </div>
          <div class="exam-result-body">
            <div class="exam-result-subtitle">重生之我在拿捏学驾考</div>
            <div class="exam-result-score">您本次考试得分{{ examScore }}分,{{ examScore < 90 ? '不合格!' : '成绩合格' }}</div>
                <div class="exam-result-hint" v-if="examScore < 90">考试机会就2次,这都不好好把握?打算再回炉重造?</div>
                <div class="exam-result-hint" v-else>该出手时就出手，别犹豫啦!小本本在朝你招手咯~</div>
            </div>
            <div class="exam-result-footer">
              <button class="exam-result-btn retry-btn" @click="retryExam">再考一次</button>
              <button class="exam-result-btn view-wrong-btn" @click="viewWrongQuestions">查看错题</button>
              <button class="exam-result-btn exit-btn" @click="exitExam">退出考试</button>
            </div>
          </div>
        </div>
      </div>
    </div>
</template>
<script setup lang="ts">
import { onMounted, ref, onUnmounted, computed } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { getSimulateQuestion, getQuestionProgress, updateExamStatus } from '@/api/userApi'
import { useUserStore } from '@/store/user'
import collected from '@/assets/img/collected.png'
import isCollected from '@/assets/img/collect.png'

const userStore = useUserStore()
const router = useRouter()
const tdHeader = ref(['题号', '1列', '2列', '3列', '4列', '5列', '6列', '7列', '8列', '9列', '10列'])
const isVisible = ref(false)
const dialogType = ref('')
const currentIndex = ref(0)
const questionList = ref<any[]>([])
const currentQuestion = computed(() => {
  if (isWrongQuestionsMode.value) {
    return wrongQuestionsList.value[currentWrongIndex.value]
  }
  return questionList.value[currentIndex.value]
})
const wrongVisible = ref(false)
const examResultVisible = ref(false)
const examScore = ref(0)
const isWrongQuestionsMode = ref(false)
const wrongQuestionsList = ref<any[]>([])
const currentWrongIndex = ref(0)

// 新增：记录错题模式下每道题是否已经切换过
const wrongQuestionTouched = ref<{ [key: number]: boolean }>({})

const correctNum = computed(() => {
  const data = isWrongQuestionsMode.value ? wrongQuestionsList.value : questionList.value
  return data.filter((q: any) => isQuestionCorrect(q)).length
})

const wrongNum = computed(() => {
  const data = isWrongQuestionsMode.value ? wrongQuestionsList.value : questionList.value
  return data.filter((q: any) => isQuestionWrong(q)).length
})

const unansweredCount = computed(() => {
  const data = isWrongQuestionsMode.value ? wrongQuestionsList.value : questionList.value
  return data.filter((q: any) => !q.userAnswer || (Array.isArray(q.userAnswer) && q.userAnswer.length === 0)).length
})

// 选项映射
const options = computed(() => {
  const q = currentQuestion.value
  if (!q) return {}

  const opts: any = {}
  if (q.questionA) opts.A = q.questionA
  if (q.questionB) opts.B = q.questionB
  if (q.questionC) opts.C = q.questionC
  if (q.questionD) opts.D = q.questionD

  return opts
})

let allowLeave = false

//考试倒计时
const countdown = ref(45 * 60)
//错题学习倒计时
const wrongCountDown = ref(10)

//获取用户作答
function getUserAnswer(index: number) {
  const data = isWrongQuestionsMode.value ? wrongQuestionsList.value : questionList.value
  const question = data[index]

  if (!question?.userAnswer) return ''
  //多选题
  if (question.questionType === 0) {
    if (Array.isArray(question.userAnswer)) {
      return question.userAnswer.slice().sort().join('')
    }
    return question.userAnswer
  }
  // 判断题：A显示✓，B显示×
  if (question.questionType === 2) {
    return question.userAnswer === 'A' ? '✓' : question.userAnswer === 'B' ? '×' : ''
  }
  // 单选题：直接显示 A/B/C/D
  return question.userAnswer
}

function isQuestionCorrect(q: any) {
  if (!q || !q.userAnswer) return false
  if (q.questionType === 0) {
    if (!Array.isArray(q.userAnswer)) return false

    let answerArray = q.answer
    if (!Array.isArray(q.answer)) {
      answerArray = q.answer.split('').sort()
    }
    if (q.userAnswer.length !== answerArray.length) return false
    const sortedUser = [...q.userAnswer].sort().join('')
    const sortedAnswer = [...answerArray].sort().join('')
    return sortedUser === sortedAnswer
  } else {
    // 单选/判断题
    return q.userAnswer === q.answer
  }
}

function isQuestionWrong(q: any) {
  if (!q || !q.userAnswer) return false
  if (q.questionType === 0) {
    if (!Array.isArray(q.userAnswer)) return true

    let answerArray = q.answer
    if (!Array.isArray(q.answer)) {
      answerArray = q.answer.split('').sort()
    }

    if (q.userAnswer.length !== answerArray.length) return true
    const sortedUser = [...q.userAnswer].sort().join('')
    const sortedAnswer = [...answerArray].sort().join('')
    return sortedUser !== sortedAnswer
  } else {
    // 单选/判断题
    return q.userAnswer !== q.answer
  }
}

// 判断是否答对
function isCorrect(index: number) {
  const data = isWrongQuestionsMode.value ? wrongQuestionsList.value : questionList.value
  const q = data[index]
  return isQuestionCorrect(q)
}

// 判断是否答错
function isWrong(index: number) {
  const data = isWrongQuestionsMode.value ? wrongQuestionsList.value : questionList.value
  const q = data[index]
  return isQuestionWrong(q)
}

// 可选：高亮当前选中
function isSelectedCell(index: number) {
  if (isWrongQuestionsMode.value) {
    return currentWrongIndex.value === index
  }
  return currentIndex.value === index
}


const formatTime = (sec: number) => {
  const m = String(Math.floor(sec / 60)).padStart(2, '0')
  const s = String(sec % 60).padStart(2, '0')
  return `${m}:${s}`
}

let examTimer: any = null      // 考试倒计时
let modalTimer: any = null     // 弹窗倒计时
const startTimer = () => {
  examTimer = window.setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      clearInterval(examTimer)
    }
  }, 1000)
}

let _next: any = null

onBeforeRouteLeave((to, from, next) => {
  if (allowLeave) {
    allowLeave = false // 重置
    next()
    return
  }
  dialogType.value = 'back'
  isVisible.value = true
  _next = next
  // 不调用 next()，页面不会跳转
})

// 交卷按钮点击
function handleSubmitClick() {
  dialogType.value = 'submit'
  isVisible.value = true
}

const submitExam = () => {
  isVisible.value = false

  // 根据当前模式计算考试分数
  let totalQuestions, correctAnswers;
  if (isWrongQuestionsMode.value) {
    totalQuestions = wrongQuestionsList.value.length
    correctAnswers = wrongQuestionsList.value.filter(q => isQuestionCorrect(q)).length
  } else {
    totalQuestions = questionList.value.length
    correctAnswers = questionList.value.filter(q => isQuestionCorrect(q)).length
  }

  examScore.value = Math.round((correctAnswers / totalQuestions) * 100)

  // 显示考试结果弹框
  examResultVisible.value = true

  if (!isWrongQuestionsMode.value) {
    submit()
    updateExamState()
  }
}
const examId = ref('')
const submit = async () => {
  let obj = {
    memberId: userStore.storeInfo.memberId,
    carModelId: userStore.storeInfo.carModelId,
    categoryId: userStore.categoryId,
    isSimulation: 1,
    examId: examId.value,
    answerRecords: [] as Array<{
      questionId: string;
      userAnswer: string;
      isCorrect: number;
      isCollected: number;
    }>
  }
  const answerSummary = questionList.value.filter((q: any) => q.userAnswer && (!Array.isArray(q.userAnswer) || q.userAnswer.length > 0))
    .map((q: any) => {
      let isCorrectVal = 0
      if (q.questionType === 0) {
        if (Array.isArray(q.userAnswer)) {
          let answerArray = q.answer
          if (!Array.isArray(q.answer)) {
            answerArray = q.answer.split('').sort()
          }

          if (q.userAnswer.length === answerArray.length) {
            const sortedUser = [...q.userAnswer].sort().join('')
            const sortedAnswer = [...answerArray].sort().join('')
            if (sortedUser === sortedAnswer) {
              isCorrectVal = 1
            }
          }
        }
      } else {
        isCorrectVal = q.userAnswer === q.answer ? 1 : 0
      }
      return {
        questionId: q.questionId,
        userAnswer: q.questionType === 0 ? (Array.isArray(q.userAnswer) ? q.userAnswer.slice().sort().join('') : q.userAnswer) : q.userAnswer,
        isCorrect: isCorrectVal,
        isCollected: q.isCollected ? 1 : 0
      }
    })
  obj.answerRecords = answerSummary
  const res = await getQuestionProgress(obj)
  if (res.code === '00000') {
    ElMessage.success('提交成功')
  }
}

const updateExamState = async () => {
  let obj = {
    memberId: userStore.storeInfo.memberId,
    examId: examId.value,
    status: 2,
    duration: countdown.value
  }
  const res = await updateExamStatus(obj)
}

const continueExam = () => {
  isVisible.value = false
  if (_next) {
    _next(false) // 阻止路由跳转
    _next = null
  }
}


const modalCountdown = () => {
  modalTimer = window.setInterval(() => {
    if (wrongCountDown.value > 0) {
      wrongCountDown.value--
    } else {
      wrongVisible.value = false
      clearInterval(modalTimer)
    }
  }, 1000)
}

// 切换题目时，如果当前题答错则弹出弹框
const selectQuestion = (index: number) => {
  if (isWrongQuestionsMode.value) {
    // 错题模式下，先检查当前题是否答错
    if (isWrong(currentWrongIndex.value)) {
      (wrongQuestionsList.value[currentWrongIndex.value]).locked = true
      wrongVisible.value = true
      wrongCountDown.value = 10
      modalCountdown()
      shouldGoNext.value = true
      targetQuestionIndex.value = index // 记住目标题目
      return
    }
    wrongQuestionTouched.value[index] = true
    currentWrongIndex.value = index
    return
  }

  if (isWrong(currentIndex.value)) {
    (questionList.value[currentIndex.value]).locked = true
    wrongVisible.value = true
    wrongCountDown.value = 10
    modalCountdown()
    shouldGoNext.value = true
    targetQuestionIndex.value = index // 记住目标题目
    return
  }
  goToQuestion(index)
  currentIndex.value = index
}

const closeModal = () => {
  wrongVisible.value = false
  if (modalTimer) clearInterval(modalTimer)
  if (shouldGoNext.value) {
    if (isWrongQuestionsMode.value) {
      // 错题模式下，跳转到目标题目
      if (targetQuestionIndex.value >= 0) {
        currentWrongIndex.value = targetQuestionIndex.value
        wrongQuestionTouched.value[targetQuestionIndex.value] = true
        targetQuestionIndex.value = -1 // 重置
      } else {
        // 如果没有目标题目，切换到下一题
        if (currentWrongIndex.value < wrongQuestionsList.value.length - 1) {
          currentWrongIndex.value++
        }
      }
    } else {
      // 正常模式下，跳转到目标题目
      if (targetQuestionIndex.value >= 0) {
        goToQuestion(targetQuestionIndex.value)
        currentIndex.value = targetQuestionIndex.value
        targetQuestionIndex.value = -1 // 重置
      } else {
        // 如果没有目标题目，切换到下一题
        if (currentIndex.value < questionList.value.length - 1) {
          currentIndex.value++
          goToQuestion(currentIndex.value)
        }
      }
    }
    shouldGoNext.value = false // 重置
  }
}

// 再考一次
const retryExam = () => {
  examResultVisible.value = false
  isWrongQuestionsMode.value = false
  currentWrongIndex.value = 0
  currentIndex.value = 0
  countdown.value = 45 * 60
  if (examTimer) {
    clearInterval(examTimer)
  }
  getData()
  startTimer()
  wrongQuestionTouched.value = {}
}

// 查看错题
const viewWrongQuestions = () => {
  examResultVisible.value = false
  isWrongQuestionsMode.value = true
  wrongQuestionsList.value = questionList.value.filter((q: any) => {
    if (!q.userAnswer || (Array.isArray(q.userAnswer) && q.userAnswer.length === 0)) return true
    return isQuestionWrong(q)
  })
  currentWrongIndex.value = 0
  currentIndex.value = 0
  countdown.value = 45 * 60
  if (examTimer) {
    clearInterval(examTimer)
  }
  startTimer()
  wrongQuestionsList.value.forEach((q: any) => {
    q.userAnswer = null
    q.locked = false
    q.hasLeft = false
  })
  wrongQuestionTouched.value = {}
}

// 退出考试
const exitExam = () => {
  examResultVisible.value = false
  if (_next) {
    _next()
    _next = null
  } else {
    allowLeave = true
    router.back()
  }
}

// 实现多选
const chooseAnswer = (key: any) => {
  if (showAnswer.value) return;
  if ((currentQuestion.value)?.locked) return;

  if (isWrongQuestionsMode.value) {
    const idx = currentWrongIndex.value
    // 对于多选题，允许重新选择，不阻止操作
    if (
      currentQuestion.value?.userAnswer &&
      wrongQuestionTouched.value[idx] &&
      currentQuestion.value.questionType !== 0
    ) {
      return;
    }
  }

  // 判断题型，0:多选, 1:单选, 2:判断
  if (currentQuestion.value.questionType === 0) {
    // 多选题
    if (!Array.isArray(currentQuestion.value.userAnswer)) {
      currentQuestion.value.userAnswer = [];
    }
    const idx = currentQuestion.value.userAnswer.indexOf(key);
    if (idx > -1) {
      currentQuestion.value.userAnswer.splice(idx, 1);
    } else {
      currentQuestion.value.userAnswer.push(key);
    }
  } else {
    // 单选/判断题
    if (currentQuestion.value.userAnswer === key) {
      currentQuestion.value.userAnswer = '';
    } else {
      currentQuestion.value.userAnswer = key;
    }
  }
}

function goPrev() {
  if (isWrongQuestionsMode.value) {
    // 错题模式下，先检查当前题是否答错
    if (isWrong(currentWrongIndex.value)) {
      (wrongQuestionsList.value[currentWrongIndex.value]).locked = true
      wrongVisible.value = true
      wrongCountDown.value = 10
      modalCountdown()
      shouldGoNext.value = true
      targetQuestionIndex.value = -1 // 上一题，不需要特定目标
      return
    }
    if (currentWrongIndex.value > 0) {
      currentWrongIndex.value--
    }
    return
  }

  if (currentIndex.value > 0) {
    currentIndex.value--
    goToQuestion(currentIndex.value)
  }
}

const shouldGoNext = ref(false)
const targetQuestionIndex = ref(-1) // 存储用户想要跳转的目标题目索引

function goNext() {
  if (isWrongQuestionsMode.value) {
    // 错题模式下，先检查当前题是否答错
    if (isWrong(currentWrongIndex.value)) {
      (wrongQuestionsList.value[currentWrongIndex.value]).locked = true
      wrongVisible.value = true
      wrongCountDown.value = 10
      modalCountdown()
      shouldGoNext.value = true
      targetQuestionIndex.value = -1 // 下一题，不需要特定目标
      return
    }
    if (currentWrongIndex.value < wrongQuestionsList.value.length - 1) {
      currentWrongIndex.value++
    }
    return
  }

  if (currentQuestion.value.userAnswer &&
    isQuestionWrong(currentQuestion.value)) {
    // 锁定当前题
    (currentQuestion.value).locked = true
    wrongVisible.value = true
    shouldGoNext.value = true
    targetQuestionIndex.value = -1 // 下一题，不需要特定目标
    modalCountdown()
    return
  }
  if (currentIndex.value < questionList.value.length - 1) {
    currentIndex.value++
    goToQuestion(currentIndex.value)
  }
}

// 判断是否显示正确答案
function goToQuestion(index: any) {
  // 如果当前题已作答，设置 hasLeft
  const cur = questionList.value[currentIndex.value]
  if (cur && cur.userAnswer && (!Array.isArray(cur.userAnswer) || cur.userAnswer.length > 0)) {
    cur.hasLeft = true
  }
  currentIndex.value = index
}

const showAnswer = computed(() => {
  return currentQuestion.value?.userAnswer &&
    (!Array.isArray(currentQuestion.value?.userAnswer) || currentQuestion.value?.userAnswer.length > 0) &&
    currentQuestion.value?.hasLeft
})

// 选题表格数据，根据 questionList.value 生成二维数组，每行10个
const questionTableRows = computed(() => {
  const data = isWrongQuestionsMode.value ? wrongQuestionsList.value : questionList.value
  const rows: Array<Array<{ index: number }>> = []
  const total = data.length
  const perRow = 10
  for (let i = 0; i < total; i += perRow) {
    const row: Array<{ index: number }> = []
    for (let j = 0; j < perRow && i + j < total; j++) {
      row.push({ index: i + j })
    }
    rows.push(row)
  }
  return rows
})

const getData = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...'
  })
  try {
    let obj = {
      carModelId: userStore.storeInfo.carModelId,
      categoryId: userStore.categoryId,
      id: userStore.storeInfo.memberId
    }
    const res = await getSimulateQuestion(obj)
    if (res.code === '00000' && res.data) {
      questionList.value = res.data.wxQuestionS
      examId.value = res.data.examId
    }
  } finally {
    loading.close()
  }
}

onMounted(() => {
  startTimer()
  getData()
})

onUnmounted(() => {
  if (examTimer) clearInterval(examTimer)
})
</script>
<style lang="scss" scoped>
@use './exam.scss' as *;
</style>
